package com.healthbox.notifications.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthbox.notifications.commom.Result;
import com.healthbox.notifications.entity.AddressRisk;
import com.healthbox.notifications.entity.HealthState;
import com.healthbox.notifications.entity.ReportInfo;
import com.healthbox.notifications.mapper.AddressRiskMapper;
import com.healthbox.notifications.mapper.HealthStateMapper;
import com.healthbox.notifications.service.AddressRiskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chs
 * @since 2022-05-12
 */
@Service
public class AddressRiskServiceImpl extends ServiceImpl<AddressRiskMapper, AddressRisk> implements AddressRiskService {

    @Resource
    private AddressRiskMapper addressRiskMapper;

    @Resource
    private HealthStateMapper healthStateMapper;

    /**
     * 变更地区风险等级
     * 函数实现
     * @author chs
     */
    @Override
    public Result updateAddressRisk(AddressRisk addressRisk,String role){
        if(role.equals("organ_admin")){
            QueryWrapper<AddressRisk> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("address", addressRisk.getAddress());
            AddressRisk query = addressRiskMapper.selectOne(queryWrapper);
            if(query==null){
                addressRiskMapper.insert(addressRisk);
            }
            else{
                addressRisk.setAid(query.getAid());
                addressRiskMapper.updateById(addressRisk);
            }

            //每次地址变更风险等级时，处于同地址的用户健康状态改变
            List<HealthState> healthStateList = healthStateMapper.selectList(new QueryWrapper<HealthState>().eq("address", addressRisk.getAddress()));
            Iterator<HealthState> iterator=healthStateList.iterator();
            while(iterator.hasNext()){
                HealthState now = iterator.next();
                now.setHealthstate(addressRisk.getRiskRank());
                healthStateMapper.updateById(now);
            }

            return Result.succeed(addressRisk);
        }
        else{
            return Result.fail("403","没有权限操作");
        }

    }

    /**
     * 查看中高风险地区
     * 函数实现
     * @author chs
     */
    @Override
    public Result getAdressRiskList() {
        QueryWrapper<AddressRisk> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("riskRank", 1)
                .or()
                .eq("riskRank",2);
        List<AddressRisk> addressRiskList = addressRiskMapper.selectList(queryWrapper);
        return Result.succeed(addressRiskList);
    }
}
